package com.nf.health.app.datamain.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.UrineTestHistoryDataAdapter;
import com.nf.health.app.customview.DragListView;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.models.UrineTestHistoryBean;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hepan on 2016/3/21.
 * The only genius that is worth anything is the genius for hard work
 * <p/>
 * 尿检数据历史记录
 */
public class UrineTestHistoryDataActivity extends BaseActivity {

    @Bind(R.id.lv_date)
    DragListView lvDate;
    @Bind(R.id.tv_glucose_value)
    TextView tvGlucoseValue;
    @Bind(R.id.tv_glucose_status)
    TextView tvGlucoseStatus;
    @Bind(R.id.tv_bilirubin_value)
    TextView tvBilirubinValue;
    @Bind(R.id.tv_bilirubin_status)
    TextView tvBilirubinStatus;
    @Bind(R.id.tv_acetone_body_value)
    TextView tvAcetoneBodyValue;
    @Bind(R.id.tv_acetone_body_status)
    TextView tvAcetoneBodyStatus;
    @Bind(R.id.tv_scale_value)
    TextView tvScaleValue;
    @Bind(R.id.tv_scale_status)
    TextView tvScaleStatus;
    @Bind(R.id.tv_red_cell_value)
    TextView tvRedCellValue;
    @Bind(R.id.tv_red_cell_status)
    TextView tvRedCellStatus;
    @Bind(R.id.tv_ph_value)
    TextView tvPhValue;
    @Bind(R.id.tv_ph_status)
    TextView tvPhStatus;
    @Bind(R.id.tv_urine_protein_value)
    TextView tvUrineProteinValue;
    @Bind(R.id.tv_urine_protein_status)
    TextView tvUrineProteinStatus;
    @Bind(R.id.tv_nitrite_value)
    TextView tvNitriteValue;
    @Bind(R.id.tv_nitrite_status)
    TextView tvNitriteStatus;
    @Bind(R.id.tv_white_cell_value)
    TextView tvWhiteCellValue;
    @Bind(R.id.tv_white_cell_status)
    TextView tvWhiteCellStatus;
    @Bind(R.id.tv_urobilinogen_value)
    TextView tvUrobilinogenValue;
    @Bind(R.id.tv_urobilinogen_status)
    TextView tvUrobilinogenStatus;
    @Bind(R.id.titlebar_right_tv)
    TextView titlebarRightTv;

    private RequestProvider provider;
    private static final String REQUEST_URINE_TEST_HISTORY = "request_urine_test_history";
    private static final String REQUEST_MORE_DATA = "request_more_data";
    private static final String DELETE_DATA = "delete_data";

    private String pageNo = "1";
    private String pageSize = "15";

    private UrineTestHistoryDataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_urine_test_history_data);
        setTitleBar(R.layout.layout_common_header);
        ButterKnife.bind(this);

        initView();
        initListener();
        provider = new RequestProvider(this);
        provider.requestUrineTestHistoryData(pageNo, pageSize, REQUEST_URINE_TEST_HISTORY);

    }

    private void initListener() {
        titlebarRightTv.setOnClickListener(this);
        lvDate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //把选择位置存储起来
                PreferenceHelper.putInt(PreferenceHelper.URINE_TEST_HISTTORY_ITEM, position);
                adapter.notifyDataSetChanged();
                //设置item对应数据
                setSelectedItemData(position);
            }
        });
    }

    /**
     * 设置点击item对应数据
     * @param position
     */
    private void setSelectedItemData(int position) {
        UrineTestHistoryBean.DataBean.DeviceDataBean deviceData = bean.data.deviceData.get(position - 1);
        tvGlucoseValue.setText(deviceData.glucose_value);
        tvGlucoseStatus.setText(deviceData.glucose_status);
        changeColor(deviceData.glucose_status.equals("正常"),tvGlucoseValue,tvGlucoseStatus);

        tvBilirubinValue.setText(deviceData.bilirubin_value);
        tvBilirubinStatus.setText(deviceData.bilirubin_status);
        changeColor(deviceData.bilirubin_status.equals("正常"),tvBilirubinStatus,tvBilirubinValue);

        tvAcetoneBodyValue.setText(deviceData.acetone_body_value);
        tvAcetoneBodyStatus.setText(deviceData.acetone_body_status);
        changeColor(deviceData.acetone_body_status.equals("正常"),tvAcetoneBodyValue,tvAcetoneBodyStatus);

        tvScaleValue.setText(deviceData.scale_value);
        tvScaleStatus.setText(deviceData.scale_status);
        changeColor(deviceData.scale_status.equals("正常"),tvScaleValue,tvScaleStatus);

        tvRedCellValue.setText(deviceData.red_cell_value);
        tvRedCellStatus.setText(deviceData.red_cell_status);
        changeColor(deviceData.red_cell_status.equals("正常"),tvRedCellValue,tvRedCellStatus);

        tvPhValue.setText(deviceData.ph_value);
        tvPhStatus.setText(deviceData.ph_status);
        changeColor(deviceData.ph_status.equals("正常"),tvPhValue,tvPhStatus);

        tvUrineProteinValue.setText(deviceData.urine_protein_value);
        tvUrineProteinStatus.setText(deviceData.urine_protein_status);
        changeColor(deviceData.urine_protein_status.equals("正常"),tvUrineProteinValue,tvUrineProteinStatus);

        tvNitriteValue.setText(deviceData.nitrite_value);
        tvNitriteStatus.setText(deviceData.nitrite_status);
        changeColor(deviceData.nitrite_status.equals("正常"),tvNitriteValue,tvNitriteStatus);

        tvWhiteCellValue.setText(deviceData.white_cell_value);
        tvWhiteCellStatus.setText(deviceData.white_cell_status);
        changeColor(deviceData.white_cell_status.equals("正常"),tvWhiteCellValue,tvWhiteCellStatus);

        tvUrobilinogenValue.setText(deviceData.urobilinogen_value);
        tvUrobilinogenStatus.setText(deviceData.urobilinogen_status);
        changeColor(deviceData.urobilinogen_status.equals("正常"),tvUrobilinogenValue,tvUrobilinogenStatus);
    }
    /**
     * 改变tv颜色
     * @param isNormal 是否正常
     * @param tvs 数组
     *
     */
    private void changeColor(boolean isNormal,TextView... tvs){
        for (int i = 0; i < tvs.length; i++) {
            if (isNormal){//正常是蓝色
                tvs[i].setTextColor(this.getResources().getColor(R.color.theme_color));
            }else{//异常时橘色
                tvs[i].setTextColor(this.getResources().getColor(R.color.theme_orange));
            }
        }
    }
    private void initView() {
        //设置标题
        ViewUtil.setText(this, R.id.titlebar_title_tv, "历史记录");
        titlebarRightTv.setVisibility(View.VISIBLE);
        ViewUtil.setText(this, R.id.titlebar_right_tv, "删除");
        lvDate.setDivider(null);

        lvDate.setRefreshableAndLoadMoreable(true, true);
        lvDate.setOnRefreshAndLoadMoreListener(new DragListView.onRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                //下拉加载-直接请求数据
//                requestData(pageNo, pageSize, REQUEST_URINE_TEST_HISTORY);
                provider.requestUrineTestHistoryData(pageNo, pageSize, REQUEST_URINE_TEST_HISTORY);

            }

            @Override
            public void onLoadMore() {
                //底部加载-请求第二页数据
                int morePage = Integer.valueOf(pageNo);
                morePage++;
//                pageNo = String.valueOf(morePage); //改变pageNo会导致重新请求时没有数据
//                requestData(String.valueOf(morePage), pageSize, REQUEST_MORE_DATA);

                provider.requestUrineTestHistoryData(String.valueOf(morePage), pageSize, REQUEST_MORE_DATA);
            }
        });
    }

    private void requestData(String pageNo, String pageSize, String httpFlag) {
        if (provider == null) {
            provider = new RequestProvider(this);
        }
        if (REQUEST_URINE_TEST_HISTORY.equals(httpFlag)) {
            //首次请求数据
            provider.requestBloodHistoryData(pageNo, pageSize, httpFlag);

        }
        if (REQUEST_MORE_DATA.equals(httpFlag)) {
            //首次更多数据
            provider.requestBloodHistoryData(pageNo, pageSize, httpFlag);
        }
    }

    private UrineTestHistoryBean bean;

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (REQUEST_URINE_TEST_HISTORY.equals(actionName)) {
            lvDate.completeRefresh();
            bean = (UrineTestHistoryBean) object;
            if (adapter == null) {
                adapter = new UrineTestHistoryDataAdapter(this, bean);
            }
            lvDate.setAdapter(adapter);
            if (bean.data.deviceData.size() > 0) {
                //请求成功展示第一条数据
                setSelectedItemData(1);
            }
        } else if (DELETE_DATA.equals(actionName)) {
            showToast("删除成功");
        } else if (REQUEST_MORE_DATA.equals(actionName)) {
            lvDate.completeLoadMore();
            UrineTestHistoryBean extra1 = (UrineTestHistoryBean) object;
            if (extra1 == null || extra1.data.deviceData.equals("[]") || extra1.data.deviceData.size() < 1) {
                showToast("没有更多数据");
            } else {
                bean.data.deviceData.addAll(extra1.data.deviceData);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_tv:
               showDeleteDialog();
                break;
            default:
                break;
        }
    }

    /**
            * 展示删除对话框
    */
    private void showDeleteDialog() {
         new AlertDialog.Builder(this)
                .setTitle("确认")
                .setMessage("确认删除?")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteHistoryData();
                    }
                }).setNegativeButton("否",null)
                .show();

    }

    /**
     * 删除历史记录
     */
    private void deleteHistoryData() {
        //获得当前选中的位置id,1代表第0个对象,因为刷新头布局占据了lv一个位置
        int position = PreferenceHelper.getInt(PreferenceHelper.BODY_FAT_HISTTORY_ITEM, 1);

        if (bean != null && bean.data.deviceData.size() >= position){
            //获得集合中对象id
            int id = bean.data.deviceData.get(position - 1).id;
            provider.requestDeleteHistory("urine", id + "", DELETE_DATA);

            //刷新界面
            bean.data.deviceData.remove(position - 1);
            adapter.notifyDataSetChanged();
        }

    }
    @Override
    protected void onStop() {
        super.onStop();
        //重新设置选中item为1 使得初次进入时为最近数据 存1时因为draglistview有一个刷新头
        PreferenceHelper.putInt(PreferenceHelper.URINE_TEST_HISTTORY_ITEM, 1);
    }
}
